﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Yt.Core.Security
{
    /// <summary>
    /// MD5加密算法
    /// </summary>
    public static class MD5
    {
        /// <summary>
        /// 获取字符串的 MD5 值
        /// </summary>
        /// <param name="text">字符串</param>
        /// <returns>MD5 值</returns>
        public static string GetMD5(string text)
        {
            if(string.IsNullOrEmpty(text))return "";
            return GetMD5(Encoding.UTF8.GetBytes(text));
        }

        /// <summary>
        /// 实现对一个文件md5的读取，path为文件路径
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string GetFileMD5(string path)
{
            if (string.IsNullOrEmpty(path)) return "";
            if (!File.Exists(path)) return "";
             using (Stream file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
             {
               return GetMD5(file);
             }
        }

        /// <summary>
        /// 获取流的 MD5 值
        /// </summary>
        /// <param name="stream">流</param>
        /// <returns>MD5 值</returns>
        public static string GetMD5(Stream stream)
        {
            byte[] hash_byte;
            using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
            {
                hash_byte = md5.ComputeHash(stream);
            }
            return GetHash(hash_byte);
        }

        /// <summary>
        /// 获取数组的 MD5 值
        /// </summary>
        /// <param name="buffer">数组</param>
        /// <param name="offset">偏移</param>
        /// <param name="count">长度</param>
        /// <returns>MD5 值</returns>
        public static string GetMD5(byte[] buffer)
        {
            byte[] hash_byte;
            using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
            {
                hash_byte = md5.ComputeHash(buffer, 0, buffer.Length);
            }
            return GetHash(hash_byte);
        }
        /// <summary>
        /// 获取数组的 MD5 值
        /// </summary>
        /// <param name="hash_byte">数组</param>
        /// <returns>MD5 值</returns>
        private static string GetHash(byte[] hash_byte)
        {
            string resule = BitConverter.ToString(hash_byte);
            resule = resule.Replace("-", "");
            return resule;
        }
    }
}